#!/usr/bin/env bash
set -euo pipefail
# Tool for hacking on the initramfs quickly.  Like
# `cosa build-fast`, this takes content just from an "overrides"
# directory, in this case overrides/initramfs (relative to the cosa workdir).
# Note that this does a literal overlay onto the initramfs,
# which bypasses dracut modules - so if you're e.g. hacking
# on a systemd unit or binary, you'll need to do so directly.
# Example usage:
# ```
# $ cd /src/ignition
# $ make
# $ install -D -m 0755 -t /srv/fcos/overrides/initramfs/usr/bin bin/amd64/ignition
# $ cd /srv/fcos
# $ cosa buildinitramfs-fast
# ```
# 
# Now you can e.g. log into it:
# $ cosa run --devshell-console --qemu-image tmp/fastbuild/fastbuildinitrd*.qcow2
# Or run tests:
# $ cosa kola run --qemu-image tmp/fastbuild/fastbuildinitrd*.qcow2 basic

dn=$(dirname "$0")
# shellcheck source=src/cmdlib.sh
. "${dn}"/cmdlib.sh
# shellcheck source=src/cmdlib.sh
. "${dn}"/libguestfish.sh

prepare_build

initramfs_overridedir=${workdir}/overrides/initramfs
if ! [ -d "${initramfs_overridedir}" ]; then
    fatal "Must have overrides/initramfs to use this command"
fi

previous_build=$(get_latest_build)
previous_qemu=
if [ -z "${previous_build}" ]; then
    fatal "previous build required for a fast build"
fi
previous_builddir=$(get_build_dir "${previous_build}")
previous_commit=$(jq -r '.["ostree-commit"]' < "${previous_builddir}/meta.json")
previous_qemu=$(jq -r '.["images"]["qemu"]["path"]' < "${previous_builddir}/meta.json")
if [ "${previous_qemu}" = "null" ]; then
    fatal "A previous qemu build is required"
fi
echo "Basing on: ${previous_qemu}"

set -x
moddir="$(ostree ls --repo "${tmprepo}" "${previous_commit}" /usr/lib/modules | awk '{ print $5 }' | tail -1)"

ostree --repo="${tmprepo}" checkout -U --force-copy --subpath="${moddir}/initramfs.img" "${previous_commit}" .

initramfs=initramfs.img
test -f "${initramfs}" || fatal "missing ${initramfs}"
(cd "${initramfs_overridedir}"
 find . -print0 | cpio -o -H newc -R root:root --null \
                --quiet --reproducible --force-local \
                -D . | gzip -1) >>"${initramfs}"

fastbuild_qemu="fastbuildinitrd-${name}-qemu.qcow2"
qemu-img create -F qcow2 -f qcow2 -o backing_file="${previous_builddir}/${previous_qemu}" "${fastbuild_qemu}" 20G

coreos_gf_run_mount ro "${fastbuild_qemu}"
coreos_gf remount /boot rw:true
destinitramfs=$(coreos_gf glob-expand /boot/ostree/*/initramfs*)
coreos_gf upload "${initramfs}" "${destinitramfs}"
coreos_gf_shutdown
cd "${workdir}"
rm "${fastbuilddir}" -rf
mv -nT "${tmp_builddir}" "${fastbuilddir}"
echo "Created: ${fastbuilddir}/${fastbuild_qemu}"
